package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;

public class SubjectDataListener extends AnalysisEventListener<SubjectData> {
//    @Autowired  //从容器中获取对象，因为当前类不是组件类  不能使用
//    SubjectMapper subjectMapper;

    SubjectMapper subjectMapper;
    public SubjectDataListener(SubjectMapper subjectMapper){
        this.subjectMapper = subjectMapper;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        //每次读取一行数据会被调用一次，将本次的数据存到数据库
        String levelOneSubjectTitle = subjectData.getLevelOneSubjectTitle();
        String levelTwoSubjectTitle = subjectData.getLevelTwoSubjectTitle();
        //判断如果一级分类没有，保存一级课程分类
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getTitle , levelOneSubjectTitle);
        queryWrapper.eq(Subject::getParentId , "0");
        Subject psubject = subjectMapper.selectOne(queryWrapper);
        if(psubject==null){
            psubject = new Subject();
            psubject.setParentId("0");
            psubject.setTitle(levelOneSubjectTitle);
            psubject.setSort(0);
            subjectMapper.insert(psubject);
        }
        //判断如果当前一级分类的二级分类不存在，保存二级课程分类
        queryWrapper.clear();
        queryWrapper.eq(Subject::getTitle , levelTwoSubjectTitle);
        queryWrapper.eq(Subject::getParentId , psubject.getId());

        Integer count = subjectMapper.selectCount(queryWrapper);
        if(count==0){
            Subject subject = new Subject();
            subject.setSort(0);
            subject.setTitle(levelTwoSubjectTitle);
            subject.setParentId(psubject.getId());
            subjectMapper.insert(subject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("excel文档解析完成");
    }
}
